import ejs from 'ejs' // 导入ejs库，用于渲染模板
import fs from 'node:fs' // 导入fs模块，用于文件系统操作
import { marked } from 'marked' // 导入marked库，用于将Markdown转换为HTML
import browserSync from 'browser-sync' // 导入browser-sync库，用于实时预览和同步浏览器
const readme = fs.readFileSync('README.md') // 读取README.md文件的内容

import express from 'express'

const router = express.Router() //路由模块
router.get('/', (req, res) => {
  const openBrowser = () => {
    const browser = browserSync.create()
    /* 生成的位置在public/md */
    browser.init({
      server: {
        baseDir: './public/md',
        index: 'index.html',
      },
    })
    return browser
  }
  ejs.renderFile(
    './views/md.ejs',
    {
      content: marked.parse(readme.toString()),
      title: 'markdown to html',
    },
    (err, data) => {
      if (err) {
        console.log(err)
      }
      let writeStream = fs.createWriteStream('./public/md/index.html')
      writeStream.write(data)
      writeStream.close()
      writeStream.on('finish', () => {
        openBrowser()
      })
    }
  )
  res.render('md', { title: 'markdown to html', content: marked.parse(readme.toString()) }) // 渲染 index 模板，并传递 title 数据
})

export default router
